package org.softmed.rest.server.defaults.boot;

import java.io.File;
import java.text.Collator;
import java.util.Comparator;

public class FileComparator implements Comparator {
	private Collator c = Collator.getInstance();

	public int compare(Object o1, Object o2) {
		if (o1 == o2)
			return 0;

		File f1 = (File) o1;
		File f2 = (File) o2;

		Integer result = compareByNumbersOnFileName(f1, f2);
		if (result != null)
			return result;

		return c.compare(f1.getName(), f2.getName());
	}

	private Integer compareByNumbersOnFileName(File f1, File f2) {

		Integer number1 = getNumberOnFileName(f1);
		Integer number2 = getNumberOnFileName(f2);

		if (number1 == null && number2 == null)
			return null;

		if (number1 == null && number2 != null)
			return -1;

		if (number1 != null && number2 == null)
			return 1;

		if (number1 > number2)
			return 1;

		if (number1 == number2)
			return null;

		if (number1 < number2)
			return -1;

		return null;
	}

	private Integer getNumberOnFileName(File f1) {
		String name = f1.getName();
		int underScoreIndex = name.indexOf('_');
		int spaceIndex = name.indexOf(' ');

		if (underScoreIndex < 0 && spaceIndex < 0)
			return getNumberInFileName(name);

		if (underScoreIndex < 0 && spaceIndex > 0)
			return getNumberFromFileName(name, spaceIndex);

		if (underScoreIndex > 0 && spaceIndex < 0)
			return getNumberFromFileName(name, underScoreIndex);

		if (underScoreIndex < spaceIndex) {
			return getNumberFromFileName(name, underScoreIndex);
		} else {
			return getNumberFromFileName(name, spaceIndex);
		}

	}

	private Integer getNumberInFileName(String name) {
		try {
			int index = name.lastIndexOf(".");
			String simpleName = name.substring(0, index);

			Integer value = Integer.valueOf(simpleName);
			return value;

		} catch (Throwable t) {
			return null;
		}
	}

	private Integer getNumberFromFileName(String name, int index) {
		String numberText = name.substring(0, index);
		try {
			Integer value = Integer.valueOf(numberText);
			return value;
		} catch (Throwable t) {
			return null;
		}
	}
}
